package com.lining.orangeservice.controller;

import com.lining.orangeservice.common.Result;
import com.lining.orangeservice.entity.dto.request.RolePermissionRequest;
import com.lining.orangeservice.entity.po.Permission;
import com.lining.orangeservice.entity.po.User;
import com.lining.orangeservice.service.AuthService;
import com.lining.orangeservice.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/role")
@Tag(name = "角色管理", description = "角色和权限管理接口")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    /**
     * 为角色分配权限
     */
    @Operation(summary = "为角色分配权限", description = "将指定权限分配给角色")
    @PostMapping("/assign-permission")
    public Result<Void> assignPermissionToRole(
            @RequestBody RolePermissionRequest request) {
        Long roleId = request.getRoleId();
        List<Long> permissionIdList = request.getPermissionIds();

        roleService.assignPermissionsToRole(roleId, permissionIdList);
        return Result.success();
    }

    /**
     * 移除角色的权限
     */
    @Operation(summary = "移除角色的权限", description = "从角色中移除指定权限")
    @PostMapping("/remove-permission")
    public Result<Void> removePermissionFromRole(
            @RequestBody RolePermissionRequest request) {
        Long roleId = request.getRoleId();
        List<Long> permissionIds = request.getPermissionIds();

        roleService.removePermissionsFromRole(roleId, permissionIds);
        return Result.success();
    }

    /**
     * 查看角色的权限
     */
    @GetMapping("/permissions")
    @Operation(summary = "查看角色的权限", description = "获取指定角色的所有权限信息")
    public Result<List<Permission>> getRolePermissions(
            @Parameter(description = "角色ID") @RequestParam Long roleId) {

        List<Permission> permissions = roleService.getPermissionsByRoleId(roleId);
        return Result.success(permissions);
    }

    /**
     * 查看用户的所有权限
     */
    @GetMapping("/user/permissions")
    @Operation(summary = "查看用户的权限", description = "获取当前登录用户的所有权限信息")
    public Result<List<Permission>> getUserPermissions() {

        User currentUser = authService.getCurrentUser();
        if (currentUser == null) {
            return Result.error(401, "用户未登录");
        }

        List<String> permissionCodes = currentUser.getPermissions().stream()
                .map(Permission::getPermCode)
                .collect(Collectors.toList());

        return Result.success(roleService.getPermissionsByUserId(currentUser.getId()));

    }

}

